import _ from 'lodash';
import { routerRedux } from 'dva/router';
import * as taskService from '../services/taskService';
import * as vipService from '../services/vipService';
import * as recommendService from '../services/recommendService';
import monent from 'moment';
import { Toast } from 'antd-mobile';

function delay(time) {
  return new Promise((res, rej) => {
    setTimeout(res, time || 1000);
  });
}

export default {
  namespace: 'task',
  state: {
    total: 0,
    0: [],
    1: [],
    2: [],
    3: [],
    4: [],
    5: [],
    6: [],
    7: [],
    8: [],
    9: [],
    10: [],
    11: [],
    12: [],
    13: [],
    14: [],
    vips0: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips1: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips2: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips3: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips4: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips5: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips7: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips8: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips9: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips10: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips11: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips12: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips50: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips51: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips52: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips53: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips54: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips55: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips6: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips60: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips61: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips62: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips63: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips70: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips71: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips72: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips73: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips74: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips101: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips120: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips121: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips122: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips123: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips124: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips125: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips126: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips127: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips128: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips129: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips1210: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips1211: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips13: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips14: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips15: { data: [], meta: { page: 0, totalPageCount: 1 } },
    vips16: { data: [], meta: { page: 0, totalPageCount: 1 } },
    subVips: [],
    visitedRecord: [],
    vipInfo: {},
    vipInfoAcc: '',
    vipConsume: [],
    recommend: [],
    tasks1: { data: [], meta: { totalCount: 0, page: 0, totalPageCount: 1, key: '' } },
    tasks2: { data: [], meta: { totalCount: 0, page: 0, totalPageCount: 1, key: '' } },
    tasks3: { data: [], meta: { totalCount: 0, page: 0, totalPageCount: 1, key: '' } },
    tasks4: { data: [], meta: { totalCount: 0, page: 0, totalPageCount: 1, key: '' } },
    tasks5: { data: [], meta: { totalCount: 0, page: 0, totalPageCount: 1, key: '' } },
    /* tasks1: [],
    tasks2: [],
    tasks3: [],*/
    // 出生
    sub: {
      5: {
        0: [],
        1: [],
        2: [],
        3: [],
        4: [],
        5: [],
        total: 0,
      },
      6: {
        0: [],
        1: [],
        2: [],
        3: [],
        total: 0,
      },
      7: {
        0: [],
        1: [],
        2: [],
        3: [],
        4: [],
        total: 0,
      },
      12: {
        0: [],
        1: [],
        2: [],
        3: [],
        4: [],
        5: [],
        6: [],
        7: [],
        8: [],
        9: [],
        10: [],
        11: [],
        total: 0,
      },
      // 定制任务需要动态获取
      // vips1011: { data: [], meta: { page: 0, totalPageCount: 1 } },
      // vips1012: { data: [], meta: { page: 0, totalPageCount: 1 } },
      // ...
    },
    itemCls: [],
    brandsTop10: [],
    tabActiveKey: '1',
    sss: true,  //是否跳转
  },
  reducers: {
    save(state, { payload }) {
      payload[101] = payload[101] || [];
      return { ...state, ...payload, total: _.flatten(_.values(payload)).length };
    },
    save2(state, { payload }) {
      return { ...state, ...payload };
    },
    saveByType(state, { payload: { data, taskType, total } }) {
      const sub = {};
      sub[taskType] = { ...state.sub[taskType], ...data };
      sub[taskType].total = total;
      return { ...state, sub: { ...state.sub, ...sub } };
    },
    saveTasks(state, { payload: { data, firstPage, key, tasks } }) {
      const result = {};
      if (!data.meta) {
        data.meta = {
          totalCount: 0,
          totalPageCount: 1,
          page: 0,
          reload: 1,
        };
      }
      if (tasks) {
        result[tasks] = {};
        result[tasks].meta = data.meta;
        result[tasks].key = key;
        if (firstPage) {
          result[tasks].data = data.data;
        } else {
          result[tasks].data = [...state[tasks].data, ...data.data];
        }
        return {
          ...state,
          ...result,
        };
      }
    },
    saveVips(state, { payload: { data, meta, page, taskType, subType } }) {
      if (_.isNil(subType)) {
        subType = '';
      }
      const result = {};
      const d = state[`vips${taskType}${subType}`];
      if (page > 1) {
        result[`vips${taskType}${subType}`] = { data: [...d.data, ...data], meta };
      } else {
        result[`vips${taskType}${subType}`] = { meta, data };
      }
      return {
        ...state,
        ...result,
      };
    },
    saveVipsNext(state, { payload }) {
      return {
        ...state,
        vips: {
          data: [...state.vips.data, ...payload.data], meta: payload.meta,
        },
      };
    },
    saveVisitedRecord(state, { payload }) {
      return { ...state, visitedRecord: payload };
    },
    saveVipInfo(state, { payload }) {
      return { ...state, vipInfo: payload };
    },
    saveVipInfoAcc(state, { payload }) {
      return { ...state, vipInfoAcc: payload };
    },
    saveVipConsume(state, { payload }) {
      return { ...state, vipConsume: payload };
    },
    saveComplete(state, { payload: { taskType, cardNo, subType } }) {
      let arr = [...state[taskType]];
      let total = state.total;
      arr = _.filter(arr, (item) => {
        return item !== cardNo;
      });

      const currentVips = { ...state[`vips${taskType}`] };
      const vips = _.filter(currentVips.data, (item) => {
        return item.card_no !== cardNo;
      });
      currentVips.data = vips;
      currentVips.meta = { ...currentVips.meta, totalCount: currentVips.meta.totalCount - 1 };
      total -= 1;
      const result = { ...state, total };
      result[`vips${taskType}`] = { ...currentVips };
      result[taskType] = arr;

      if (subType) {
        let subIds = state.sub[taskType][subType];
        subIds = _.filter(subIds, (item) => {
          return item !== cardNo;
        });
        result.sub[taskType][subType] = subIds;
      }
      result.task1 = _.filter(result.task1, (v) => {
        return v.card_no !== cardNo;
      });
      return result;
    },
    saveRecommend(state, { payload }) {
      return { ...state, recommend: payload };
    },
    clearTasks(state, { payload }) {
      return {
        ...state,
        tasks1: { data: [], meta: { totalCount: 0, page: 0, totalPageCount: 1 } },
        tasks2: { data: [], meta: { totalCount: 0, page: 0, totalPageCount: 1 } },
        tasks3: { data: [], meta: { totalCount: 0, page: 0, totalPageCount: 1 } },
      };
    },
    saveItemCls(state, { payload }) {
      return { ...state, itemCls: payload.data };
    },
    saveBrandsTop10(state, { payload }) {
      return { ...state, brandsTop10: payload.data };
    },
    saveTabActiveKey(state, { payload }) {
      return { ...state, tabActiveKey: payload.data };
    },
  },
  effects: {
    * stv({ payload }, { call, put, select}) {
      yield put({type: 'save2', payload: {sss: payload}})
    },
    * fetch({ payload: { branchId } }, { call, put, select }) {
      const { shopId, salemanId, branchNo, roles } = yield select(state => state.auth.currentUser);
      if (!shopId) return;
      const result = yield call(taskService.fetch, shopId, branchId || branchNo, salemanId);

      if (!result.data[0]) {
        result.data[0] = [];
      }
      for (let i = 3; i <= 14; i++) {
        if (!result.data[i]) {
          result.data[i] = [];
        }
      }
      yield put({ type: 'save', payload: result.data });
    },
    * fetchByType({ payload: { taskType, total } }, { call, put, select }) {
      const { shopId, salemanId, branchNo, roles } = yield select(state => state.auth.currentUser);
      const result = yield call(taskService.fetch, shopId, branchNo, salemanId, taskType);
      yield put({ type: 'saveByType', payload: { data: result.data, taskType, total } });
    },
    * complete({ payload: { taskType, subType, cardNo, completeType, reason, way, salemanId: sid } },
      { put, select, call }) {
      const { shopId, salemanId } = yield select(state => state.auth.currentUser);
      yield call(taskService.complete,
        shopId, salemanId, cardNo, completeType, reason, way, taskType, subType);
      if (completeType === 1) {
        yield put({ type: 'saveComplete', payload: { taskType, cardNo, subType } });
      }
      yield put({ type: 'home/tip', payload: { type: 'success', message: '完成回访' } });
      yield delay();
      yield put(routerRedux.go(-2));
    },
    * fetchVips({ payload: { taskType, page, subType, pageSize, filter } }, { put, select }) {
      // let ids = yield select(state => state.task[taskType] || []);
      // if (subType) {
      //   ids = yield select(state => state.task.sub[taskType][subType] || []);
      //   pageSize = 100;
      // }
      const { shopId, branchNo, salemanId, roles } = yield select(state => state.auth.currentUser);
      if (taskType) {
        taskType = parseInt(taskType);
      }
      if (subType) {
        subType = parseInt(subType);
      }
      let match = {
        shopId,
        branch_no: branchNo,
        saleman_id: salemanId,
        taskType,
        subType,
        ...filter,
      };
      match = _.pickBy(match, (v) => {
        return !_.isNil(v);
      });
      const result = yield vipService.fetch(page, pageSize, match);
      if (shopId === 'qez_1111111') {
        result.data.forEach((v) => {
          const tel = v.vip_tel || v.mobile;
          v.vip_tel = _.padEnd(tel.substr(0, 7), 11, '*');
          v.mobile = _.padEnd(tel.substr(0, 7), 11, '*');
        });
      }
      yield put({ type: 'saveVips', payload: { ...result, page, taskType, subType } });
    },
    * fetchVisitedRecord({ payload: { cardNo } }, { put, select }) {
      const { shopId, salemanId } = yield select(state => state.auth.currentUser);
      const result = yield vipService.fetchVisitedRecord(shopId, salemanId, cardNo);
      yield put({ type: 'saveVisitedRecord', payload: result.data });
    },

    * editVisitRecds({ payload: { id, remark } }, { put, select }) {
      const { data } = yield vipService.editVisitRecds(id, remark);
      if (data.ok) {
        let { visitedRecord } = yield select(state => state.task);
        visitedRecord = visitedRecord.map((item) => {
          if (item._id === id) {
            item.remark = remark;
          }
          return item;
        });
        yield put({ type: 'saveVisitedRecord', payload: visitedRecord });
        setTimeout(() => {
          Toast.success('修改成功', 1);
        }, 20);
      } else {
        setTimeout(() => {
          Toast.fail('修改失败', 1);
        }, 20);
      }
    },

    * fetchVipInfo({ payload: { card_id } }, { put, select }) {
      const { shopId } = yield select(state => state.auth.currentUser);
      const result = yield vipService.fetchVipInfo(shopId, card_id);
      if (shopId === 'qez_1111111') {
        const tel = result.data.vip_tel || result.data.mobile;
        result.data.vip_tel = _.padEnd(tel.substr(0, 7), 11, '*');
      }
      yield put({ type: 'saveVipInfo', payload: result.data });

      // 把以前的备注合并入标签
      const { remarks, vip_tags } = result.data;
      if (remarks && remarks.trim()) {
        const { query } = yield select(state => state.routing.locationBeforeTransitions);
        let label = [];
        label = vip_tags.map(item => item.text);
        label.push(remarks.trim());
        yield put({ type: 'vip/editLabel', payload: { cardNo: query.cardNo, label } });

        const { _id } = yield select(state => state.task.vipInfo);
        yield put({ type: 'vip/updateRemarks', payload: { _id, cardNo: query.cardNo, remarks: '' } });
      }
    },
    * fetchVipConsume({ payload: { card_id } }, { put, select }) {
      const { shopId } = yield select(state => state.auth.currentUser);
      const result = yield vipService.fetchVipConsume(shopId, card_id);
      yield put({ type: 'saveVipConsume', payload: result.data });
    },
    fetchNextPageVip: [function* ({ payload: { taskType, subType, filter } }, { put, select }) {
      let { page } = yield select(state => state.task[`vips${taskType}${subType || ''}`].meta);
      page = parseInt(page, 10) + 1;
      yield put({ type: 'fetchVips', payload: { page, taskType, subType, filter } });
    }, { type: 'takeLatest' }],
    * fetchRecommend({ payload: { taskType, subType, card_no } }, { put, select }) {
      const { shopId } = yield select(state => state.auth.currentUser);
      const result = yield recommendService.fetch(taskType, subType, shopId, card_no);
      yield put({ type: 'saveRecommend', payload: result.data });
    },
    * fetchMyTasks({ payload: { complete, success, isExpired, tasks, key, firstPage, startDate, endDate, isBranch } }, { put, select }) {
      let { shopId, salemanId, branchNo, roles } = yield select(state => state.auth.currentUser);
      const { branchPickerValue } = yield select(state => state.stat);

      if (!_.includes(roles, 'manager') && branchPickerValue && branchPickerValue.length > 0 && branchPickerValue[0] && branchPickerValue[0] !== '全部') {
        branchNo = branchPickerValue[0];
      }

      let nextPage;
      if (firstPage) {
        nextPage = 1;
      } else {
        const { page } = yield select(state => state.task[tasks].meta);
        nextPage = page + 1;
      }
      if (key == undefined) {
        key = yield select(state => state.task[tasks].key);
      }


      if (isBranch) {
        salemanId = null;
      } else {
        salemanId = salemanId || null;
      }

      const result = yield taskService.fetchMyTask(shopId, branchNo, salemanId, complete, success, isExpired, nextPage, key, startDate, endDate);
      console.log({ data: result, firstPage, key, tasks });
      yield put({ type: 'saveTasks', payload: { data: result, firstPage, key, tasks } });
    },
    * fetchItemCls({ payload }, { put, select }) {
      const { itemCls } = yield select(state => state.task);
      if (!_.isEmpty(itemCls)) return;
      const { shopId } = yield select(state => state.auth.currentUser);
      const result = yield taskService.fetchItemCls(shopId);
      yield put({ type: 'saveItemCls', payload: result });
    },
    * fetchVipAcc({ payload: { shopId, cardNo } }, { call, put, select }) {
      const result = yield vipService.fetchVipAcc(shopId, cardNo);
      yield put({ type: 'saveVipInfoAcc', payload: result.data.remain_acc });
    },
    * fetchBrandsTop10({ payload }, { put, select }) {
      const { shopId } = yield select(state => state.auth.currentUser);
      const { brandsTop10 } = yield select(state => state.task);
      if (!_.isEmpty(brandsTop10)) return;
      // const result = yield taskService.fetchBrandsTop10(shopId, monent().subtract(3, 'months').toISOString(), monent().toISOString());
      const result = yield taskService.fetchBrandsTop10(shopId);
      yield put({ type: 'saveBrandsTop10', payload: result });
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query }) => {
        if (pathname === '/p1') {
          // dispatch({ type: 'fetchVips', payload: query });
        }
        if (pathname === '/p6') {
          dispatch({ type: 'fetchByType', payload: query });
        }
        if (pathname === '/p50') {
          dispatch({ type: 'fetchByType', payload: { ...query, taskType: '6' } });
          dispatch({ type: 'fetchByType', payload: { ...query, taskType: '7' } });
        }
        if (pathname === '/p12') {
          dispatch({ type: 'fetchByType', payload: query });
        }
        if (pathname === '/myTasks') {
          // dispatch({ type: 'clearTasks' });
          // dispatch({ type: 'fetchMyTasks', payload: { complete: 0 ,tasks:'tasks1', save:true} });
        }
      });
    },
  },
};
